<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input v-model="query.name" clearable placeholder="名字" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">功能参数</label>
        <el-input v-model="query.param" clearable placeholder="功能参数" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1000px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="130px" inline>
          <el-form-item label="所属图层">
            <el-select v-model="form.mapId.id" style="width: 650px;" placeholder="请选择">
              <el-option v-for="item in mapList" :key="item.id" :label="item.name" :value="item.id" @click.native="bindSelectMap(item)" />
            </el-select>
          </el-form-item>
          <el-form-item label="家具名字">
            <el-input v-model="form.name" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="功能参数">
            <el-input v-model="form.param" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="过期时间">
            <el-date-picker v-model="form.expireTime" type="datetime" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="质保年限">
            <el-input v-model="form.year" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="负责人电话">
            <el-input v-model="form.dutyTel" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="负责人">
            <el-input v-model="form.dutyPerson" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="品牌">
            <el-input v-model="form.brand" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="来源">
            <el-input v-model="form.source" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="x轴">
            <el-input v-model="form.gisX" :readonly="true" style="width: 250px;">
              <el-button slot="prepend" icon="el-icon-search" @click.native="getPoint()" />
            </el-input>
          </el-form-item>
          <el-form-item label="y轴">
            <el-input v-model="form.gisY" :readonly="true" style="width: 250px;">
              <el-button slot="prepend" icon="el-icon-search" @click.native="getPoint()" />
            </el-input>
          </el-form-item>

          <el-form-item label="图片" style="width: 800px;">
            <el-upload
              :action="imagesUploadApi + '?name=' + form.picName"
              list-type="picture-card"
              :limit="3"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="onBeforeUpload"
              :headers="headers"
              :file-list="form.pictureList"
              accept="image/jpeg,image/jpg,image/png"
            >
              <i class="el-icon-plus" />
            </el-upload>
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="form.price" style="width: 250px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog :append-to-body="true" :visible.sync="mapPointDialog" title="地点定位" top="2vh" width="1250px">
        <div style="height:72vh;width:100%;">
          <MapPoint v-if="mapPointDialog" ref="mapPoint" :map-id="selectMap" :gis-x="form.gisX" :gis-y="form.gisY" @clickCallback="mapCallback" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button :loading="false" type="primary" @click="mapCancel">确定</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="家具名称" />
        <el-table-column prop="param" label="功能参数" />
        <el-table-column prop="expireTime" label="过期时间" />
        <el-table-column prop="year" label="质保年限" />
        <el-table-column prop="dutyTel" label="负责人电话" />
        <el-table-column prop="dutyPerson" label="负责人" />
        <el-table-column prop="brand" label="品牌" />
        <el-table-column prop="source" label="来源" />
        <el-table-column prop="path" label="预览图">
          <template slot-scope="scope">
            <span v-if="scope.row.picPath">
              <span
                v-for="(item, i) in scope.row.picPath.split('|') "
                :key="i"
              >
                <el-image
                  v-if="item!=''"
                  :src="baseApi + item"
                  :preview-src-list="getPreviewSrcList(scope.row.picPath)"
                  fit="contain"
                  lazy
                  class="el-avatar"
                >
                  <div slot="error">
                    <i class="el-icon-document" />
                  </div>
                </el-image>
              </span>
            </span>
            <!-- <div v-if="scope.row.picPath">
              <div>

                <el-image v-for="(item) in getPicArr(scope.row.picPath)" :key="item" :src=" baseApi + item" :preview-src-list="[baseApi + item]" fit="contain" lazy class="el-avatar">
                  <div slot="error"> <i class="el-icon-document" /> </div>
                </el-image>
              </div>
            </div> -->
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column v-if="checkPer(['admin','houseEle:edit','houseEle:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudBasicMap from '@/api/basicMap'
// import BaseMap from '@/views/map/basicMap/BaseMap.vue'
import crudHouseEle from '@/api/houseEle'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import MapPoint from '@/views/components/MapPoint'

const defaultForm = { gisX: null, gisY: null, mapId: { id: null }, pictureList: [],
  id: null, name: null, type: '1', param: null, expireTime: null, year: null, dutyTel: null, dutyPerson: null, brand: null, source: null, picPath: null, price: null, createBy: null, createTime: null }
export default {
  name: 'HouseEle',
  components: { MapPoint, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '家具', url: 'api/houseEle', idField: 'id', sort: 'id,desc', crudMethod: { ...crudHouseEle }})
  },
  data() {
    return {
      mapList: [],
      mapPointDialog: false,
      selectMap: {},
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'houseEle:add'],
        edit: ['admin', 'houseEle:edit'],
        del: ['admin', 'houseEle:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'name', display_name: '家具家电名字' },
        { key: 'type', display_name: '类型1家具2家电' },
        { key: 'param', display_name: '功能参数' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi'
    ])
  },
  mounted() {
    this.query.name = this.$route.query.name
    this.crud.toQuery()
    this.getMaps()
  },
  methods: {
    getPreviewSrcList(data) {
      if (data.split('|')) {
        var previewList = []
        var arr = data.substr(0, data.length - 1).split('|')
        for (var i = 0; i < arr.length; i++) {
          previewList.push(this.baseApi + arr[i])
        }
        return previewList
      } else {
        return []
      }
    },
    mapCancel() {
      this.mapPointDialog = false
    },
    mapCallback(data) {
      this.form.gisX = data[0].toFixed(5)
      this.form.gisY = data[1].toFixed(5)
    },
    bindSelectMap(row) {
      this.selectMap = row
    },
    getPoint() {
      if (this.form.mapId.id === null) {
        this.$message.error('请先选择地图')
      } else {
        this.mapPointDialog = true
      }
    },
    getMaps() {
      crudBasicMap.getAll().then((res) => {
        this.mapList = res
      })
    },
    getPicArr(data) {
      var arr = data.split('|')
      arr.pop()
      return arr
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.query.type = '1'
      return true
    },
    [CRUD.HOOK.beforeToEdit]() {
      this.selectMap = this.form.mapId
    },

    [CRUD.HOOK.afterToCU](crud, form) {
      if (this.form.picPath) {
        var arr = this.form.picPath.split('|')
        for (var i = 0; i < arr.length; i++) {
          if (arr[i]) {
            var array = arr[i].split('/')
            this.form.pictureList.push({
              'url': this.baseApi + arr[i],
              response: { 'realName': array[3], 'type': array[2] }
            })
          }
        }
      }
    },
    handleSuccess(response, file, fileList) {
      console.log(file)
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    // 图片上传超出最大数量
    handleExceed(file, fileList) {
      this.$message({
        message: '每条最多上传三张图片',
        center: true,
        type: 'warning'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.picPath = ''
      for (var i = 0; i < fileList.length; i++) {
        this.form.picPath += '/file/' + fileList[i].response.type + '/' + fileList[i].response.realName + '|'
      }
    },
    onBeforeUpload(file) {
      const isIMAGE = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png')
      const isLt1M = file.size / 1024 / 1024 < 100

      if (!isIMAGE) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.picName = file.name
      return isIMAGE && isLt1M
    },
    handlePreview(file) {
      var a = this.$refs['downloadA']
      a.href = this.baseApi + '/file/' + file.response.type + '/' + file.response.realName
      a.click()
    }
  }
}
</script>

<style>
#map {
  height: 100%;
  width: 100%;
}
.ol-attribution,
.ol-zoom {
  display: none;
}
</style>
